function sendSize() {
    var w = $("input[name='w']")[0].value;
    var h = $("input[name='h']")[0].value;
    $.ajax({
        url: "/initField",
        type: "POST",
        data: JSON.stringify({'width': w, 'height': h }),
        contentType: 'application/json',
        dataType: 'json'
    }).success(function (data) {
            if (data.errorCode != 0) {
                return;
            }
            createTable(data.height, data.width);
        })
}

var isZero = false;
$("input[name='w']").change(function(){updateStartEnabled()});
$("input[name='h']").change(function(){updateStartEnabled()});
$("#teamName").change(function(){updateSendButtonState();});
var fileSelected=false;

function createTable(height, width) {
    $('.playboard').empty();
    var w = $('.playboard').width();
    var h = $('.playboard').height() - 100;
    var table = $('<table></table>').addClass('boardTable');

    for (var i = 0; i < height; i++) {
        var row = $('<tr></tr>');
        table.append(row);
        for (var j = 0; j < width; j++) {
            var cell = $('<td><div class="cell r' + i + 'c' + j + '"></div></td>');
            cell.click(function () {
                var th = $(this);
                if (!th.hasClass("cross") && !th.hasClass("zero")) {
                    if (isZero) {
                        th.addClass("zero");
                        isZero = false;
                    } else {
                        th.addClass("cross");
                        isZero = true;
                    }
                }
            })
            row.append(cell);
        }
    }
    var cellHeight = Math.floor(h / height);
    var cellWidht = Math.floor(w / width);
    var cellSize = Math.min(cellHeight, cellWidht);


    $('.playboard').append(table);

    $('.playboard tr td').width(cellSize);
    $('.playboard tr td').height(cellSize);
    $('.playboard tr').height(cellSize);
    $(table).css("margin-left", ($('.playboard').width() - table.width()) / 2);
}

$(function () {
    $('#fileupload').fileupload({
        add: function (e, data) {
            var children=$("label[for='fileupload']").children()[0];
            fileSelected=data.files.length>0;
            $("label[for='fileupload']").empty().append(children).append($('<span></span>').text(" "+data.files[0].name))
            updateSendButtonState();
            data.context = $('#sendFileButton').off('click')
                .click(function () {
                    var input = $('#teamName');
                    data.formData = {teamName: input.val()};
                    if (data.formData.teamName) {
                        data.submit();
                    }
                });
        },
        done:  function (e, data) {updateTeamList(data.result);
            $('#teamName').val('');
            var children=$("label[for='fileupload']").children()[0];
            $("label[for='fileupload']").empty().append(children).append($('<span></span>').text(" Choose file"));
            fileSelected=false;
            updateSendButtonState();
        },
        fail: function(e, data) {
            alert('Fail!');
        }
    });
});

function updateSendButtonState(){
    $('#sendFileButton').attr('disabled', !(fileSelected &&  $('#teamName').val()!=null &&  $('#teamName').val().trim()!=""))
}

    $.ajax({
        url: "/getTeams",
        type: "POST",
        contentType: 'application/json',
        dataType: 'json'
    }).success(updateTeamList)

function updateTeamList(data){
    if (data == null) {
        return;
    }
    var teamList1 = $('#teamList1').empty();
    var teamList2 = $('#teamList2').empty().attr('selection','-1');
    var teamListButton1 =   $('#dropdownMenu1');
    var teamListButton2 =   $('#dropdownMenu2');
    var teamSelector1= $('#teamSelector1').attr('selection','-1');
    var teamSelector2 =   $('#teamSelector2').attr('selection','-1');
    for (var i=0; i<data.length; i++) {
        teamList1.append(createTeamItem(data[i], teamSelector1, i,teamListButton1));
        teamList2.append(createTeamItem(data[i], teamSelector2, i,teamListButton2));
    }

}

function createTeamItem(item, combobox, index, btn){
    var l = $('<li></li>').attr('role', 'presentation');
    var a= $('<a></a>').attr('role', 'menuitem').attr('tabindex', '-1').attr('href', '#').text(item.name);
    a.click(function(){
        combobox.attr('selection',''+index);
        btn.text(item.name);
        updateStartEnabled();
    })
    l.append(a)
    return l;
}

function isInt(n){
    return !isNaN(Number(n)) && n%1===0;
}

function updateStartEnabled(){
    var firstSelectionIndex =  $('#teamSelector1').attr('selection');
    var secondSelectionIndex =  $('#teamSelector2').attr('selection');
    var w = $("input[name='w']")[0].value;
    var h = $("input[name='h']")[0].value;
    var sizeCorrect = isInt(w) && Number(w)>5 && isInt(h) && Number(h)>5;
    var disabled = firstSelectionIndex=="-1" || secondSelectionIndex=="-1" || firstSelectionIndex== secondSelectionIndex || !sizeCorrect;
    $('#startButton').attr('disabled', disabled);
}


function start(){
    var w = $("input[name='w']")[0].value;
    var h = $("input[name='h']")[0].value;
    var team1 =  $("#teamSelector1").attr('selection');
    var team2 =  $("#teamSelector2").attr('selection');
    $('#player1Time').text('00:00:00:000');
    $('#player2Time').text('00:00:00:000');
    $('.winTitle').hide();
    $.ajax({
        url: "/start",
        type: "POST",
        data: JSON.stringify({'w': w, 'h': h , 'p1':team1,'p2':team2}),
        contentType: 'application/json',
        dataType: 'json'
    }).success(function (res) {
         nextState();
        })
}

function nextState(){
    $.ajax({
        url: "/getState",
        type: "POST"
    }).success(function (data) {
            drawTable(data);
            updateState(data);
            if (""+data.finished!="true"){
                setTimeout(function(){ nextState();}, 800);
            } else {
                if (""+data.winner=="1"){
                    $('#player1Win').show().text('WINS!')
                } else  if (""+data.winner=="2"){
                    $('#player2Win').show().text('WINS!')
                } else {
                    alert('DRAW!');
                }
            }
        })
}

function updateState(data){
    $('#player1Time').text(data.firstPlayerTime);
    $('#player2Time').text(data.secondPlayerTime);
}

function drawTable(data){
    createTable(data.h, data.w);
    var table =  $('.boardTable')[0];
    for (var i=0; i<data.cellStateList.length; i++){
        var cellState = data.cellStateList[i];
        var cell = $(table)[0].rows[cellState.y].cells[cellState.x];
        $(cell).addClass(cellState.mark=='X'?'cross':'zero');
    }

}

